import globalVersion from '@/../public/version/index.js'

const state = {
  version: globalVersion.version,
  checking: false,
  updateContent: [],
  onlineVersion: [0, 0, 0],
  onlineVersionUrl: 'https://xue5hen.gitee.io/x-vue-electron-demo/api/version.json'
}

const getters = {
}

const mutations = {
  checkingSetter (state, params) {
    state.checking = params
  },
  onlineVersionSetter (state, params) {
    state.onlineVersion = params
  },
  updateContentSetter (state, params) {
    state.updateContent = params || []
  }
}

const actions = {
  // 与线上版本做对比
  checkVersion ({ state, commit }, {vm}) {
    if (state.checking) return Promise.reject('正在检测中')
    commit('checkingSetter', true)
    return vm.$jstools.ajax.get(state.onlineVersionUrl).then((res) => {
      if (res.data && res.data.success) {
        let updateContent = (res.data.data || {}).content
        let onlineVersion = (res.data.data || {}).version.split('.')
        let compareResult = vm.$jstools.compareVersions(onlineVersion, state.version)
        commit('onlineVersionSetter', onlineVersion)
        commit('updateContentSetter', updateContent)
        return compareResult.slice(0, 3)
      } else {
        return '查询失败'
      }
    }).finally(() => {
      commit('checkingSetter', false)
    })
  },
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
